<template>
	<div class="watch">
		<p>
    Ask a yes/no question:
    <input v-model="question" />
  </p>
  <p>{{ answer }}</p>
	</div>
</template>

<script setup lang="ts">
import { ref,watch,onWatcherCleanup,watchEffect } from 'vue'
const question = ref('')
const answer = ref('Questions usually contain a question mark. ;-)')
const loading = ref(false)

const x = ref(0)
const y = ref(0)

watch(x, (newX, oldX) => {
	console.log(`x changed from ${oldX} to ${newX}`)
})
watch(()=>x.value+y.value, (newValue, oldValue) => {
	console.log(`sum changed from ${oldValue} to ${newValue}`)
})
watch([x,()=>y.value], ([newX, newY], [oldX, oldY]) => {
	console.log(`x and y changed from ${oldX} and ${oldY} to ${newX} and ${newY}`)
})

watch(question, async (newQuestion, oldQuestion) => {
	if (newQuestion.includes('?')) {
		loading.value = true
		answer.value = 'Loading...'
		const controller = new AbortController()
		onWatcherCleanup(() => {
			console.log(111);
			controller.abort()
		})
		try {
			let a = await new Promise((resolve, reject) => {
				setTimeout(() => {
					resolve(222)
				}, 2000)
			})
			console.log(a);
			const res = await fetch('https://yesno.wtf/api', { signal: controller.signal })
      answer.value = (await res.json()).answer
		} catch (error) {
			answer.value = 'Error fetching answer' + error
		} finally {
			loading.value = false
		}
		
	}
})
const cleanWatch = watchEffect(()=>{})
cleanWatch()

</script>

<style scoped>

</style>